package com.dns.customers.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dns.customers.AppPage;
import com.dns.customers.dao.CustomerDao;
import com.dns.customers.model.*;
import com.dns.framework.data.IData;
import com.dns.framework.data.IDataset;
import com.dns.framework.page.Pagination;
import com.util.DataSourceUtil;
import com.util.DateUtil;
import com.util.DesUtil;
import com.util.StringUtil;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Repository
public class CustomerDaoImpl extends DataSourceUtil implements CustomerDao {


    /**
     * 根据客户ID校验客户信息是否存在
     * @param custId
     * @return
     */
    @Override
    public boolean checkIsExistsByCustId(String custId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" select count(1) cnt from DNS_CUSTOMER_INFO a  where a.cust_id = :CUST_ID ");
        long count=0;
        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("CUST_ID",custId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        //因为List中只有一个元素，所以取第一个元素即可
        Map map =resultList.get(0);
        count= (long) map.get("CNT");
        return count==0?false:true;
    }
    /**
     * 保存大客户信息
     * @param customerJson
     * @return
     */
    public String addCustomerAccount(String customerJson) throws Exception{

        //将JSON 数据 转换为JavaBean
        Customers customers = JSON.parseObject(customerJson, new TypeReference<Customers>() {});
        //取出大客户账户信息Account,然后入库
        List<Account> accountList = customers.getAccount();
        //保存客户基本信息的SQL
        StringBuffer custInfoSql= new StringBuffer();
        custInfoSql.append("insert into dns_customer_info (CUST_ID,COMPANY,TEL,PHONE,EMAIL,CONFIG_COUNT,FLUSH_COUNT,RESOLV_COUNT,UPDATE_TIME,IP,CUST_PASSWORD,EMERENCY_CONTRACT,EMERGENCY_CONTRACT_TEL,CUST_MANAGER,CUST_MANAGER_TEL,COMPANY_ADDRESS)");
        custInfoSql.append(" values(:CUST_ID,:COMPANY,:TEL,:PHONE,:EMAIL,:CONFIG_COUNT,:FLUSH_COUNT,:RESOLV_COUNT,:update_time,:IP,:CUST_PASSWORD,:EMERENCY_CONTRACT,:EMERGENCY_CONTRACT_TEL,:CUST_MANAGER,:CUST_MANAGER_TEL,:COMPANY_ADDRESS) ");
        //保存客户日志的SQL
        StringBuffer custLogSql = new StringBuffer();
        custLogSql.append(" insert into dns_customer_info_log(LOG_ID,CUST_ID_MANAGE,IN_IP,OPEARTE_TYPE,CUST_ID,CUST_PASS,IP,COMPANY,TEL,PHONE,EMAIL,CONFIG_COUNT,FLUSH_COUNT,RESOLV_COUNT,UPDATE_TIME,REMARK,EMERENCY_CONTRACT,EMERGENCY_CONTRACT_TEL,CUST_MANAGER,CUST_MANAGER_TEL,COMPANY_ADDRESS)");
        custLogSql.append(" values (:LOG_ID,:CUST_ID_MANAGE,:IN_IP,:OPEARTE_TYPE,:CUST_ID,:CUST_PASSWORD,:IP,:COMPANY,:TEL,:PHONE,:EMAIL,:CONFIG_COUNT,:FLUSH_COUNT,:RESOLV_COUNT,:update_time,:REMARK,:EMERENCY_CONTRACT,:EMERGENCY_CONTRACT_TEL,:CUST_MANAGER,:CUST_MANAGER_TEL,:COMPANY_ADDRESS)");

        //管理客户信息
        User user = customers.getUser();

        //日志流水ID
        String logId=getLogId();
        Date now =DateUtil.getCurrentTime();

        for( Account account :accountList){

            MapSqlParameterSource customerInfoParam =new MapSqlParameterSource();
            customerInfoParam.addValue("CUST_ID",account.getLoginName());
            //密码需要DES加密
            String custPasswd =DesUtil.encrypt(account.getLoginPwd());
            customerInfoParam.addValue("CUST_PASSWORD", custPasswd);
            customerInfoParam.addValue("IP",account.getIp());
            customerInfoParam.addValue("update_time",now);

            //************************客户基本信息START*********************************
            customerInfoParam.addValue("COMPANY",account.getCompany());
            customerInfoParam.addValue("TEL",account.getTel());
            customerInfoParam.addValue("PHONE",account.getPhone());
            customerInfoParam.addValue("EMAIL",account.getEmail());
            customerInfoParam.addValue("CONFIG_COUNT",account.getConfigCount());
            customerInfoParam.addValue("FLUSH_COUNT",account.getFlushCount());
            customerInfoParam.addValue("RESOLV_COUNT",account.getResolvCount());
            customerInfoParam.addValue("REMARK","新增客户");
            //客户经理和紧急联系人添加
            customerInfoParam.addValue("EMERENCY_CONTRACT",account.emerencyConTract);
            customerInfoParam.addValue("EMERGENCY_CONTRACT_TEL",account.getEmerencyContractTel());
            customerInfoParam.addValue("CUST_MANAGER",account.getCustManager());
            customerInfoParam.addValue("CUST_MANAGER_TEL",account.getCustManagerTel());
            customerInfoParam.addValue("COMPANY_ADDRESS",account.getCompanyAddress());
            System.out.println(customerInfoParam.toString());
            daoManager.update(custInfoSql.toString(),customerInfoParam);
            //客户保存日志记录
            customerInfoParam.addValue("LOG_ID",logId);
            customerInfoParam.addValue("CUST_ID_MANAGE",user.getName());
            customerInfoParam.addValue("IN_IP",user.getAccessIp());
            //操作类型 ： 新增、修改、删除
            customerInfoParam.addValue("OPEARTE_TYPE","I");

            //保存大客户操作的日志记录
            daoManager.update(custLogSql.toString(),customerInfoParam);
            //************************客户基本信息END*********************************
            //************************客户的根域名信息START****************************
            CustomerDomain customerDomain =account.getCustomerDomain();
            //根域名信息
            List<RootDomain> rootDomainList = customerDomain.getRootDomain();
            //判断根域名记录是否为空 ,新增时至少要有一个根域名
            if(rootDomainList.size()==0){
                return "根域名不能为空！";
            }
            StringBuffer domainSql = new StringBuffer();
            //插入之前先进行判断
            domainSql.append(" INSERT INTO DNS_DOMAIN_INFO(CUST_ID,DOMAIN_NAME,DOMAIN_TYPE,UPDATE_TIME,REAMRK) ");
            domainSql.append(" SELECT A.CUST_ID,:DOMAIN_NAME,:DOMAIN_TYPE,:UPDATE_TIME,:REMARK ");
            domainSql.append(" FROM DNS_CUSTOMER_INFO A ");
            domainSql.append(" WHERE A.CUST_ID=:CUST_ID ");
            domainSql.append(" AND NOT EXISTS  (SELECT 1 FROM DNS_DOMAIN_INFO B ");
            domainSql.append(" WHERE B.CUST_ID = A.CUST_ID ");
            domainSql.append(" AND B.DOMAIN_NAME = :DOMAIN_NAME ");
            domainSql.append(" AND B.DOMAIN_TYPE=:DOMAIN_TYPE) ");

            //循环根域名信息
            for(RootDomain rootDomain:rootDomainList){

                MapSqlParameterSource domainParam =new MapSqlParameterSource();
                domainParam.addValue("CUST_ID",account.getLoginName());
                //0==>代表根域名
                domainParam.addValue("DOMAIN_TYPE","0");

                // 根域名名称
                domainParam.addValue("DOMAIN_NAME",rootDomain.getDomainName());
                // 根域名备注
                domainParam.addValue("REMARK",rootDomain.getRemark());
                //  根域名没有上级节点，不填
                //  domainParam.addValue("PARENT_DOMAIN_ID",now);

                domainParam.addValue("UPDATE_TIME",now);
                daoManager.update(domainSql.toString(),domainParam);

                //根域名操作日志记录
                StringBuffer custDomainLogSql= new StringBuffer();
                custDomainLogSql.append("insert into dns_domain_info_log(LOG_ID,CUST_ID,OPERATE_TYPE,DOMAIN_TYPE,DOMAIN_NAME,UPDATE_TIME)");
                custDomainLogSql.append(" values(:LOG_ID,:CUST_ID,:OPERATE_TYPE,:DOMAIN_TYPE,:DOMAIN_NAME,:UPDATE_TIME)");
                domainParam.addValue("OPERATE_TYPE","I"); //新增操作
                domainParam.addValue("LOG_ID",logId);//日志流水ID
                //保存日志操作记录
                daoManager.update(custDomainLogSql.toString(),domainParam);
            }
            //************************客户的根域名信息END************************
        }
        //TODO 返回成功信息处理
        String result="大客户创建成功";
        return  result;
    }
    /**
     * 修改大客户信息
     * @param customerJson
     * @return
     */
    @Override
    public String modifyCustomerAccount(HttpServletRequest request,String customerJson) throws  Exception{
        //将JSON 数据 转换为JavaBean
        Customers customers = JSON.parseObject(customerJson, new TypeReference<Customers>() {});
        //取出大客户账户信息Account,然后入库
        List<Account> accountList = customers.getAccount();

        //保存客户基本信息的SQL
        StringBuffer custInfoSql= new StringBuffer();
        custInfoSql.append("update dns_customer_info set COMPANY=:COMPANY,TEL=:TEL,PHONE=:PHONE,EMAIL=:EMAIL," +
                "CONFIG_COUNT=:CONFIG_COUNT,FLUSH_COUNT=:FLUSH_COUNT,RESOLV_COUNT=:RESOLV_COUNT," +
                "UPDATE_TIME=:UPDATE_TIME,ip=:IP,CUST_PASSWORD=:CUST_PASSWORD,CUST_MANAGER=:CUST_MANAGER," +
                "CUST_MANAGER_TEL=:CUST_MANAGER_TEL,EMERENCY_CONTRACT=:EMERENCY_CONTRACT,EMERGENCY_CONTRACT_TEL=:EMERGENCY_CONTRACT_TEL," +
                "COMPANY_ADDRESS=:COMPANY_ADDRESS" );
        custInfoSql.append(" where cust_id=:CUST_ID ");
        //保存客户日志的SQL
        StringBuffer custLogSql = new StringBuffer();
        custLogSql.append(" insert into dns_customer_info_log(LOG_ID,CUST_ID_MANAGE,IN_IP,OPEARTE_TYPE,CUST_ID,CUST_PASS,IP,COMPANY,TEL,PHONE,EMAIL,CONFIG_COUNT,FLUSH_COUNT,RESOLV_COUNT,UPDATE_TIME,REMARK)");
        custLogSql.append(" values (:LOG_ID,:CUST_ID_MANAGE,:IN_IP,:OPEARTE_TYPE,:CUST_ID,:CUST_PASSWORD,:IP,:COMPANY,:TEL,:PHONE,:EMAIL,:CONFIG_COUNT,:FLUSH_COUNT,:RESOLV_COUNT,:UPDATE_TIME,:REMARK)");

        //管理客户信息
        User user = customers.getUser();

        //日志流水ID
        String logId=getLogId();
        Date now =DateUtil.getCurrentTime();

        for( Account account :accountList){

            //**********************大客户密码信息START***************************
            MapSqlParameterSource customerInfoParam =new MapSqlParameterSource();
            customerInfoParam.addValue("CUST_ID",account.getLoginName());
            String custPasswd =DesUtil.encrypt(account.getLoginPwd());
            customerInfoParam.addValue("CUST_PASSWORD", custPasswd);
            customerInfoParam.addValue("IP",account.getIp());
            customerInfoParam.addValue("UPDATE_TIME",now);
            //**********************大客户密码信息END**************************

            //************************客户基本信息START*********************************
            customerInfoParam.addValue("COMPANY",account.getCompany());
            customerInfoParam.addValue("TEL",account.getTel());
            customerInfoParam.addValue("PHONE",account.getPhone());
            customerInfoParam.addValue("EMAIL",account.getEmail());
            customerInfoParam.addValue("CONFIG_COUNT",account.getConfigCount());
            customerInfoParam.addValue("FLUSH_COUNT",account.getFlushCount());
            customerInfoParam.addValue("RESOLV_COUNT",account.getResolvCount());
            customerInfoParam.addValue("CUST_MANAGER",account.getCustManager());
            customerInfoParam.addValue("CUST_MANAGER_TEL",account.getCustManagerTel());
            customerInfoParam.addValue("EMERENCY_CONTRACT",account.getEmerencyConTract());
            customerInfoParam.addValue("EMERGENCY_CONTRACT_TEL",account.getEmerencyContractTel());
            customerInfoParam.addValue("COMPANY_ADDRESS",account.getCompanyAddress());
            customerInfoParam.addValue("REMARK","修改客户");

            daoManager.update(custInfoSql.toString(),customerInfoParam);
            //客户保存日志记录
            customerInfoParam.addValue("LOG_ID",logId);
            customerInfoParam.addValue("CUST_ID_MANAGE",user.getName());
            customerInfoParam.addValue("IN_IP", new AppPage().getRemoteAddr(request));
            //操作类型 ： 新增、修改、删除
            customerInfoParam.addValue("OPEARTE_TYPE","U");

            //保存大客户操作的日志记录
            daoManager.update(custLogSql.toString(),customerInfoParam);
            //************************客户基本信息END*********************************

            //************************客户的根域名信息START****************************
            CustomerDomain customerDomain =account.getCustomerDomain();
            if (customerDomain != null){

                //根域名信息
                List<RootDomain> rootDomainList = customerDomain.getRootDomain();
                StringBuffer domainSql = new StringBuffer();
                domainSql.append(" INSERT INTO DNS_DOMAIN_INFO(CUST_ID,DOMAIN_TYPE,DOMAIN_NAME,UPDATE_TIME,REAMRK) ");
                domainSql.append(" VALUES(:CUST_ID,:DOMAIN_TYPE,:DOMAIN_NAME,:UPDATE_TIME,:REMARK)");

                //循环根域名信息
                for(RootDomain rootDomain:rootDomainList){
                    // 判断根域名是否是新增的，若是存在的，则不做任何处理. 若不存在，则为该客户新增域名
                    boolean isDomainExists=  checkDomainIsExists(account.getLoginName(),rootDomain.getDomainName());
                    //若域名不存在，新增域名信息
                    if(!isDomainExists) {
                        //主键ID
                        MapSqlParameterSource domainParam = new MapSqlParameterSource();
                        domainParam.addValue("CUST_ID", account.getLoginName());
                        //0==>代表根域名
                        domainParam.addValue("DOMAIN_TYPE", "0");
                        // 根域名名称
                        domainParam.addValue("DOMAIN_NAME", rootDomain.getDomainName());
                        //  根域名没有上级节点，不填
                        //  domainParam.addValue("PARENT_DOMAIN_ID",now);
                        domainParam.addValue("UPDATE_TIME", now);
                        domainParam.addValue("REMARK", rootDomain.getRemark());
                        //TODO 修改时若根域名信息存在，则不进行修改
                        daoManager.update(domainSql.toString(), domainParam);
                        //根域名操作日志记录
                        StringBuffer custDomainLogSql = new StringBuffer();
                        custDomainLogSql.append("insert into dns_domain_info_log(LOG_ID,CUST_ID,OPERATE_TYPE,DOMAIN_TYPE,DOMAIN_NAME,UPDATE_TIME)");
                        custDomainLogSql.append(" values(:LOG_ID,:CUST_ID,:OPERATE_TYPE,:DOMAIN_TYPE,:DOMAIN_NAME,:UPDATE_TIME)");
                        domainParam.addValue("OPERATE_TYPE", "I"); //新增操作
                        domainParam.addValue("LOG_ID", logId);//日志流水ID
                        //保存日志操作记录
                        daoManager.update(custDomainLogSql.toString(), domainParam);
                        //如果有解析结果就保存
                        if(rootDomain.getRecord() != null){
                            StringBuffer insertRecordSql = new StringBuffer();
                            insertRecordSql.append("insert into dns_domain_record (DOMAIN_NAME,DOMAIN_TYPE,TYPE,RES,UPDATE_TIME,REMARK) ");
                            insertRecordSql.append("values (:DOMAIN_NAME,:DOMAIN_TYPE,:TYPE,:RES,:UPDATE_TIME,:REMARK)");
                            StringBuffer insertRecordLogSql = new StringBuffer();
                            insertRecordLogSql.append("insert into dns_domain_info_log(LOG_ID,DOMAIN_NAME,DOMAIN_TYPE,OPERATE_TYPE,TYPE,RES,UPDATE_TIME,REMARK) ");
                            insertRecordLogSql.append("values(:LOG_ID,:DOMAIN_NAME,:DOMAIN_TYPE,:OPERATE_TYPE,:TYPE,:RES,:UPDATE_TIME,:REMARK) ");
                            for (Record record : rootDomain.getRecord()){
                                domainParam.addValue("TYPE",record.getType());
                                domainParam.addValue("RES",record.getRes());
                                domainParam.addValue("REMARK","添加解析记录");
                                daoManager.update(insertRecordSql.toString(),domainParam);
                            }
                        }
                    }
                }
                //************************客户的根域名信息END************************
            }
        }
        //TODO 返回成功信息处理
        String resulut="大客户修改成功.";
        return  resulut;
    }
    /**
     * 根据custid查询大客户
     * @param custId 大客户id
     * @return 存在:返回Map，不存在：返回null
     */
    @Override
    public  Map<String,Object> queryUserById(String custId){
        if (custId == null || "".equals(custId))return null;
        StringBuffer sql = new StringBuffer();
        sql.append("select CUST_ID,COMPANY,TEL,PHONE,EMAIL,CONFIG_COUNT,FLUSH_COUNT," +
                "RESOLV_COUNT,UPDATE_TIME,REMARK,CUST_PASSWORD,IP,EMERENCY_CONTRACT," +
                "EMERGENCY_CONTRACT_TEL,CUST_MANAGER,CUST_MANAGER_TEL,COMPANY_ADDRESS " +
                " from dns_customer_info where cust_id=:CUSTID");

        MapSqlParameterSource param = new MapSqlParameterSource("CUSTID",custId);
        List<Map<String,Object>> result = daoManager.queryForList(sql.toString(),param);
        if (result != null && result.size() > 0)return result.get(0);

        return null;
    }
    /**1、删除大客户信息
     * 2、删除大客户下的根域名信息.
     * 3、删除根域下的子域名信息
     * 3、删除根域名和子域名对应的解析记录信息
     *
     * @param customerJson
     * @return
     */

    public String deleteCustomerAccount(HttpServletRequest request,String customerJson)  throws  Exception{
        boolean mode = false;
        //日志流水ID
        String logId=getLogId();
        Date now =DateUtil.getCurrentTime();
        //将JSON 数据 转换为JavaBean
        Customers customerObject = JSON.parseObject(customerJson, new TypeReference<Customers>() {});
        //取出大客户账户信息Account
        List<Account> accountList = customerObject.getAccount();
        User user = customerObject.getUser();

        //=====================日志记录SQL START============================
        //操作客户日志的SQL
        StringBuffer custLogSql = new StringBuffer();
        custLogSql.append(" insert into dns_customer_info_log(LOG_ID,CUST_ID_MANAGE,IN_IP,OPEARTE_TYPE,CUST_ID,CUST_PASS,IP,COMPANY,TEL,PHONE,EMAIL,CONFIG_COUNT,FLUSH_COUNT,RESOLV_COUNT,UPDATE_TIME,REMARK)");
        custLogSql.append(" values (:LOG_ID,:CUST_MANAGER,:IN_IP,:OPEARTE_TYPE,:CUST_ID,:CUST_PASSWORD,:IP,:COMPANY,:TEL,:PHONE,:EMAIL,:CONFIG_COUNT,:FLUSH_COUNT,:RESOLV_COUNT,:UPDATE_TIME,:REMARK)");
        //操作根域名日志的SQL
        StringBuffer custDomainLogSql= new StringBuffer();
        custDomainLogSql.append("insert into dns_domain_info_log(LOG_ID,CUST_ID,OPERATE_TYPE,DOMAIN_TYPE,DOMAIN_NAME,PARENT_DOMAIN_NAME,UPDATE_TIME)");
        custDomainLogSql.append(" values(:LOG_ID,:CUST_ID,:OPERATE_TYPE,:DOMAIN_TYPE,:DOMAIN_NAME,:PARENT_DOMAIN_NAME,:UPDATE_TIME)");
        //域名解析记录日志记录
        StringBuffer insetDomainLog = new StringBuffer();
        insetDomainLog.append("INSERT INTO dns_domain_record_log (LOG_ID,DOMAIN_NAME,DOMAIN_TYPE,OPERATE_TYPE,TYPE,RES,UPDATE_TIME,REMARK)");
        insetDomainLog.append(" values (:LOG_ID,:DOMAIN_NAME,:DOMAIN_TYPE,:OPERATE_TYPE,:TYPE,:RES,:UPDATE_TIME,:REMARK)");
        //=====================日志记录SQL END==============================

        MapSqlParameterSource deleteParam = null;
        StringBuffer deleteCustSql = new StringBuffer();
        StringBuffer deleteCustDomain = new StringBuffer();
        StringBuffer deleteCustDomainRecord = new StringBuffer();
        StringBuffer queryRecordList = new StringBuffer();

        try{
            for(Account account:accountList){
                //获取要删除的客户ID。
                String custIdStr =account.getLoginName();
                //删除的大客户账户账户名称；可配置多个，用分号隔开
                String[] custIds = custIdStr.split(";");
                for (String custId : custIds){
                    queryRecordList.setLength(0);
                    deleteCustSql.setLength(0);
                    deleteCustDomain.setLength(0);
                    deleteCustDomainRecord.setLength(0);
                    //若配置此项时，为删除根域名，不配置此项时，为删除大客户
                    if (account.getCustomerDomain() == null){
                        //删除大客户SQL
                        deleteCustSql.append(" delete from dns_customer_info  where cust_id=:CUST_ID ");
                        //删除客户域名信息
                        deleteCustDomain.append(" delete from DNS_DOMAIN_INFO  where cust_id=:CUST_ID ");
                        //删除域名对应的解析记录信息
                        deleteCustDomainRecord.append(" delete from DNS_DOMAIN_RECORD  where domain_name=:DOMAIN_NAME ");
                        //查询解析记录
                        queryRecordList.append("select TYPE,RES from DNS_DOMAIN_RECORD  where domain_name=:DOMAIN_NAME");
                        // 得先查出数据库中删除大客户的记录信息，保存日志在删除操作之前发生
                        deleteParam =new MapSqlParameterSource();
                        deleteParam.addValue("CUST_ID",custId);
                        Map<String,Object> cust =  queryUserById(custId);
                        if (cust != null){
                            //删除客户信息
                            daoManager.update(deleteCustSql.toString(),deleteParam);
                            //记录客户删除日志
                            cust.put("LOG_ID",logId);
                            cust.put("CUST_ID_MANAGE",user.getName());
                            cust.put("OPEARTE_TYPE","D");
                            cust.put("IN_IP",new AppPage().getRemoteAddr(request));
                            cust.put("UPDATE_TIME",now);
                            cust.put("REMARK","删除大客户");
                            daoManager.update(custLogSql.toString(),cust);
                            mode = true;
                        }
                        //获取客户的域名ID列表(domain_id)
                        List<Map<String,Object>>  domainNameList=  getDomainNameListByCustId(custId);
                        //删除域名信息
                        daoManager.update(deleteCustDomain.toString(),deleteParam);
                        //批量删除域名解析记录信息
                        for(Map map :domainNameList){
                            //域名日志记录
                            map.put("LOG_ID",logId);
                            map.put("CUST_ID",custId);
                            map.put("OPERATE_TYPE","D");
                            map.put("UPDATE_TIME",now);
                            map.put("REMARK","删除域名");
                            daoManager.update(custDomainLogSql.toString(),map);
                            //删除解析记录
                            List<Map<String,Object>> recordList = daoManager.queryForList(queryRecordList.toString(),map);
                            int a = daoManager.update(deleteCustDomainRecord.toString(),map);
                            if (a>0 && recordList != null){
                                //解析记录日志记录
                                map.put("REMARK","删除解析记录");
                                for(Map<String,Object> record : recordList){
                                    map.put("TYPE",record.get("TYPE"));
                                    map.put("RES",record.get("RES"));
                                    daoManager.update(insetDomainLog.toString(),map);
                                }
                            }
                        }
                    }else{
                        //删除客户域名信息
                        deleteCustDomain.append(" delete from DNS_DOMAIN_INFO  where CUST_ID=:CUST_ID and DOMAIN_NAME=:DOMAIN_NAME");
                        //查询解析记录
                        queryRecordList.append("select TYPE,RES from DNS_DOMAIN_RECORD  where domain_name=:DOMAIN_NAME");
                        //删除域名对应的解析记录信息
                        deleteCustDomainRecord.append(" delete from DNS_DOMAIN_RECORD  where domain_name=:DOMAIN_NAME ");
                        CustomerDomain customerDomain = account.getCustomerDomain();
                        List<RootDomain> rootDomain = customerDomain.getRootDomain();
                        if (rootDomain != null){
                            for (RootDomain root : rootDomain){
                                MapSqlParameterSource param = new MapSqlParameterSource();
                                param.addValue("CUST_ID",custId);
                                param.addValue("DOMAIN_NAME",root.getDomainName());
                                Map<String,Object> domain = queryDomainByName(custId,root.getDomainName());
                                if (domain == null)
                                    continue;
                                daoManager.update(deleteCustDomain.toString(),param);
                                //域名日志记录
                                domain.put("LOG_ID",logId);
                                domain.put("CUST_ID",custId);
                                domain.put("OPERATE_TYPE","D");
                                domain.put("UPDATE_TIME",now);
                                domain.put("REMARK","删除域名");
                                daoManager.update(custDomainLogSql.toString(),domain);
                                //删除解析记录
                                List<Map<String,Object>> recordList = daoManager.queryForList(queryRecordList.toString(),domain);
                                int a = daoManager.update(deleteCustDomainRecord.toString(),domain);
                                if (a>0 && recordList != null){
                                    //解析记录日志记录
                                    domain.put("REMARK","删除解析记录");
                                    for(Map<String,Object> record : recordList){
                                        domain.put("TYPE",record.get("TYPE"));
                                        domain.put("RES",record.get("RES"));
                                        daoManager.update(insetDomainLog.toString(),domain);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            throw  e;
        }
        log.debug("Hello World");
        return mode?"删除大客户成功":"删除根域名成功";
    }
    /**
     * 根据客户名称查询客户列表
     * @param custName
     * @param pagination
     * @return
     */
    @Override
    public IDataset queryCustListByName(String custName, Pagination pagination) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT CUST_ID,COMPANY CUST_NAME,TEL,CUST_MANAGER,CUST_MANAGER_TEL,RESOLV_COUNT,CONFIG_COUNT,FLUSH_COUNT");
        sql.append(" FROM DNS_CUSTOMER_INFO A WHERE A.COMPANY LIKE '%' :CUST_NAME '%'");
        Map param = new HashMap();
        param.put("CUST_NAME",custName);
        IDataset datasetList= daoManager.queryForListByPage(sql.toString(),param,pagination);
        return datasetList;
    }

    /**
     * 查询大客户信息（包含域名信息）
     * @param custId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryAccoundDomain(String custId) throws Exception{
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            //客户查询
            String userSql ="select cust_id loginName,company,tel,phone,email,config_count configCount,flush_count flushCount," +
                    "resolv_count resolvCount,update_time,remark,cust_password loginPwd,ip,emerency_contract emerencyConTract,emergency_contract_tel emerencyContractTel," +
                    "cust_manager custManager,cust_manager_tel custManagerTel,company_address companyAddress from dns_customer_info where CUST_ID=:CUST_ID";
            //域名查询
            String rootDomain = "select cust_id,domain_type,domain_name domainName," +
                    "parent_domain_name,update_time,reamrk from dns_domain_info where CUST_ID=:CUST_ID";
            //解析记录查询
            String records = "select dr.domain_name domainName,dr.domain_type,dr.type,dr.res,dr.update_time,dr.remark from " +
                    "dns_domain_record dr left join dns_domain_info di on dr.DOMAIN_NAME=di.DOMAIN_NAME " +
                    "where di.CUST_ID=:CUST_ID";
            MapSqlParameterSource paramMap = new MapSqlParameterSource();
            paramMap.addValue("CUST_ID",custId);
            List<Map<String,Object>> userList = daoManager.queryForList(userSql,paramMap);
            if (userList == null || userList.size()<=0){
                resultMap.put("errorCode","没有查询到客户信息");
                resultMap.put("errorMsg","没有查询到客户信息");
                return resultMap;
            }
            List<Map<String,Object>> rootDomainList = daoManager.queryForList(rootDomain,paramMap);
            List<Map<String,Object>> recordList = daoManager.queryForList(records,paramMap);
            //将解析记录放到对应的域名下
            if (rootDomainList != null && rootDomainList.size()>0){
                for (Map<String,Object> map : rootDomainList){
                    String rootName = map.get("domainName")+"";
                    if (recordList!= null && recordList.size()>=0){
                        for (Map<String,Object> record : recordList){
                            if (rootName.equals(record.get("domainName")+"")){
                                List<Map<String,Object>> list = (List)map.get("records");
                                if (list == null){
                                    list = new ArrayList<Map<String,Object>>();
                                }
                                list.add(record);
                                map.put("records",list);
                            }
                        }
                    }
                }
            }
            //将子域名放到根域名下
            if (rootDomainList != null && rootDomainList.size()>0){
                for (Map<String,Object> map1 : rootDomainList){
                    String rootName = map1.get("domainName")+"";
                    for (Map<String,Object> map2 : rootDomainList){
                        if (rootName.equals(map2.get("parent_domain_name")+"")){
                            List<Map<String,Object>> list = (List)map1.get("childs");
                            if (list == null){
                                list = new ArrayList<Map<String,Object>>();
                            }
                            list.add(map2);
                            map1.put("childs",list);
                        }
                    }
                }
                Iterator it = rootDomainList.iterator();
                while (it.hasNext()){
                    Map<String,Object> map1= (Map<String, Object>) it.next();
                    if ("1".equals(map1.get("DOMAIN_TYPE")+"")){
                        it.remove();
                    }
                }
            }
            //将根域名绑定到客户上
            Map<String,Object> userMap = userList.get(0);
            userMap.put("rootDomains",rootDomainList);
            String pwd = DesUtil.base64Encode(DesUtil.decrypt(userMap.get("loginPwd")+""));
            userMap.put("loginPwd",pwd);
            resultMap.put("errorMsg","查询成功");
            resultMap.put("user",userMap);
            return resultMap;
        }catch (Exception e){
            throw  e;
        }
    }
    /**
     * 查询所有域名类型
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getDnsResTypes(Map param) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT  DATA_CODE value ,DATA_NAME label  FROM TD_B_DNS_STATIC ");
        sql.append(" where VALIDFLAG=:VALIDFLAG  ");
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        return resultList;
    }
    /**
     * 查询大客户
     * @param custId 客户
     * @return 客户集合
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryCustomerAccount(String custId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" select  a.CUST_PASSWORD,a.CUST_ID,a.COMPANY,a.IP,a.TEL,a.PHONE,a.EMAIL,a.CONFIG_COUNT,a.FLUSH_COUNT,a.RESOLV_COUNT,EMERENCY_CONTRACT,EMERGENCY_CONTRACT_TEL,CUST_MANAGER,CUST_MANAGER_TEL,COMPANY_ADDRESS  from dns_customer_info a  where a.cust_id=:cust_id ");
        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("cust_id",custId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        if(resultList == null || resultList.size() <= 0){
            resultList = null;
        }
        return resultList;
    }

    /**
     * 根据客户id查询客户域名信息
     * @param custId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryParentname(String custId) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT i.domain_name,i.parent_domain_name,i.domain_type,(SELECT GROUP_CONCAT(r.TYPE SEPARATOR ';') FROM dns_domain_record r WHERE r.DOMAIN_NAME=i.DOMAIN_NAME) as type  FROM dns_domain_info i WHERE i.CUST_ID=:cust_id");
        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("cust_id",custId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        if(resultList == null || resultList.size() <= 0){
            resultList = null;
        }
        return resultList;
    }
    /**
     * 查询在途中的未完成订单信息
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String,Object>> getOrderInfoByCustId(Map param) throws Exception {

        StringBuffer sql = new StringBuffer();
        sql.append( " SELECT  a.ORDER_ID,  a.CUST_ID, b.COMPANY,a.DOMAIN_NAME,");
        sql.append( " IF(60-timestampdiff(SECOND, CREATE_DATE, NOW())>0,60-timestampdiff(SECOND, CREATE_DATE, NOW()),0) validTime,");
        sql.append(" DATE_FORMAT(a.CREATE_DATE,'%Y-%m-%d %H:%i:%s') CREATE_DATE,");
        sql.append(" DATE_FORMAT(a.UPDATE_TIME,'%Y-%m-%d %H:%i:%s') UPDATE_TIME, ");
        sql.append(" a.CLIENT_IP, a.TASK_TYPE, a.TASK_STATUS,a.STATUS_DESC,a.TASK_DESC, a.DNS_TYPE,a.REMARK ");
        sql.append(" FROM DNS_ORDER a,dns_customer_info b ");
        sql.append(" WHERE a.CUST_ID=:CUST_ID ");
        sql.append(" AND  a.CUST_ID=b.CUST_ID ");
        sql.append(" AND  A.TASK_STATUS IN (:TASK_STATUS)" );
        sql.append(" ORDER BY  A.UPDATE_TIME DESC ");
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        if (resultList == null || resultList.size() <= 0)
            return null;
        return resultList;
    }
    /**
     * 根据客户ID和域名类型查询客户归属的域名信息
     * @param custId
     * @param domain_type
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryDomainnameByIDAndType(String custId, String domain_type) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT domain_name as value,domain_name as label,domain_type as type from dns_domain_info WHERE CUST_ID = :cust_id");
        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("cust_id",custId);
        if(domain_type != null && !"".equals(domain_type)){
            param.addValue("domain_type",domain_type);
            sql.append(" AND DOMAIN_TYPE = :domain_type");
        }
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        return resultList;
    }
    /**
     * 分页查询域名列表
     * @param custID
     * @param pagination
     * @return
     * @throws Exception
     */
    @Override
    public IDataset queryRecordInfo(String custID,Pagination pagination) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT " +
                "dd.DOMAIN_NAME domainName," +
                "dd.domain_type ," +
                "dd.PARENT_DOMAIN_NAME parent_domain," +
                "dd.REAMRK remark," +
                "(SELECT GROUP_CONCAT(TYPE SEPARATOR ';') FROM dns_domain_record " +
                "WHERE DOMAIN_NAME=dd.DOMAIN_NAME AND DOMAIN_TYPE=dd.DOMAIN_TYPE ) type " +
                "FROM dns_domain_info dd WHERE dd.CUST_ID = :CUST_ID " +
                "ORDER BY dd.UPDATE_TIME DESC");
        Map param =new HashMap();
        param.put("CUST_ID",custID);
        IDataset resultList= daoManager.queryForListByPage(sql.toString(),param,pagination);
        return resultList;
    }
    /**
     * 根据多个条件查询订单及其详细信息
     * @param param
     * @param pagination
     * @return
     * @throws Exception
     */
    public IDataset queryOrder(IData param ,Pagination pagination) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT order_id, cust_id, domain_name,");
        sql.append(" DATE_FORMAT(CREATE_DATE,'%Y-%m-%d %H:%i:%s') create_date,");
        sql.append(" task_type, task_status,");
        sql.append(" DATE_FORMAT(UPDATE_TIME,'%Y-%m-%d %H:%i:%s') update_time");
        sql.append(" FROM dns_order WHERE 1=1 ");
        if(!StringUtil.checkIsEmpty(param.getString("domainname"))){
            param.put("domainname","%"+param.getString("domainname")+"%");
            sql.append(" AND DOMAIN_NAME like :domainname");
        }
        if(!StringUtil.checkIsEmpty(param.getString("createTime1"))){
            sql.append(" AND CREATE_DATE > :createTime1");
        }
        if(!StringUtil.checkIsEmpty(param.getString("createTime2"))){
            sql.append(" AND CREATE_DATE < :createTime2");
        }
        if(!StringUtil.checkIsEmpty(param.getString("orderId"))){
            sql.append(" AND ORDER_ID = :orderId");
        }
        if(!StringUtil.checkIsEmpty(param.getString("custId"))){
            sql.append(" AND CUST_ID = :custId");
        }
        if(!StringUtil.checkIsEmpty(param.getString("taskStatus"))){
            sql.append(" AND TASK_STATUS = :taskStatus");
        }
        sql.append(" order by create_date desc ");
        IDataset  resultList= daoManager.queryForListByPage(sql.toString(),param,pagination);
        return resultList;
    }

    /**
     * 查看订单详情
     * @param orderId 订单id
     * @return
     */
    @Override
    public List<Map<String, Object>> queryOrderMore(String orderId) {

        StringBuffer sql = new StringBuffer();
        sql.append("SELECT domain_name," +
                " DATE_FORMAT(CREATE_DATE,'%Y-%m-%d %H:%i:%s') create_date, " +
                " IF(60-timestampdiff(SECOND, CREATE_DATE, NOW())>0,60-timestampdiff(SECOND, CREATE_DATE, NOW()),0) validTime, " +
                " UPDATE_STAFF_ID," +
                " TIMESTAMPDIFF(MINUTE,create_date,update_time) as duration, " +
                " DATE_FORMAT(CREATE_DATE,'%Y-%m-%d %H:%i:%s') update_time, " +
                " task_type, status_desc, task_desc, task_status FROM dns_order WHERE order_id = :orderId");
        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("orderId",orderId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);

        return resultList;
    }
    /**
     * 获取省份信息
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getAllProvinces(Map param) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT  AREA_CODE value ,AREA_NAME label  FROM td_m_china_area ");
        sql.append(" where  area_level=:AREA_LEVEL ");
        sql.append(" and VALIDFLAG=:VALIDFLAG ");
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        return resultList;
    }
    public Map<String,Object> queryDomainByName(String custId,String domainName) throws  Exception{
        String sql = "select * from dns_domain_info where CUST_ID=:CUST_ID and DOMAIN_NAME=:DOMAIN_NAME";
        MapSqlParameterSource map = new MapSqlParameterSource();
        map.addValue("CUST_ID",custId);
        map.addValue("DOMAIN_NAME",domainName);
        List<Map<String,Object>> list = daoManager.queryForList(sql,map);
        if (list!=null && list.size()>0) return list.get(0);

        return  null;
    }

    /**
     * 根据客户ID获取域名列表
     * @param custId
     * @return
     */
    public  List<Map<String,Object>> getDomainNameListByCustId(String custId){

        StringBuffer sql = new StringBuffer();
        sql.append("select a.DOMAIN_NAME,a.DOMAIN_TYPE,a.PARENT_DOMAIN_NAME from DNS_DOMAIN_INFO a where a.CUST_ID=:CUST_ID ");

        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("CUST_ID",custId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);

        return resultList;
    }

    /**
     * 判断域名信息是否存在
     * @param domainName
     * @return
     */
    public boolean checkDomainIsExists(String custId,String domainName) {

        StringBuffer sql = new StringBuffer();

        sql.append(" select count(1) cnt from DNS_DOMAIN_INFO a  where a.CUST_ID=:CUST_ID and a.DOMAIN_NAME = :DOMAIN_NAME ");

        long count=0;

        MapSqlParameterSource param =new MapSqlParameterSource();
        param.addValue("DOMAIN_NAME",domainName);
        param.addValue("CUST_ID",custId);
        List<Map<String,Object>>  resultList= daoManager.queryForList(sql.toString(),param);
        //因为List中只有一个元素，所以取第一个元素即可
        Map map =resultList.get(0);
        count= (long) map.get("CNT");

        return count==0?false:true;
    }


    /**
     * 分页查询根域名详情
     * @param custId 客户id
     * @return
     */
    public IDataset queryRootDomainPage(String  custId,Pagination pagination) throws Exception{
        IDataset result = null;
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("select DOMAIN_NAME domainName,DOMAIN_TYPE domainType,reamrk from dns_domain_info where CUST_ID=:CUST_ID ");
            sql.append("and DOMAIN_TYPE='0' ORDER BY UPDATE_TIME desc");
            Map map = new HashMap();
            map.put("CUST_ID",custId);
            result = daoManager.queryForListByPage(sql.toString(),map,pagination);
        }catch (Exception e){
            throw e;
        }
        return result;
    }
}
